package com.cskaoyan.shiro;

import com.cskaoyan.model.MarketUser;
import com.cskaoyan.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

//自定的Realm要继承AuthorizingRealm
@Component
public class CustomRealm extends AuthorizingRealm {
    @Autowired
    UserService userService;

    //1. doGetAuthenticationInfo：获得认证信息  → credentials
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //1.1 authenticationToken：是subject.login传入的参数 new UsernamePasswordToken(username, password)
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;

        //1.2 subject.login中的UsernamePasswordToken中的username
        String username = token.getUsername();
        //1.3 根据用户名查询数据库中用户信息
        MarketUser marketUser = userService.findByName(username);
        //1.4 获取系统内的密码(凭证)
        String credentials = null;
        credentials = marketUser.getPassword();

        //1.5 构建身份验证信息对象
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(marketUser.getId(), credentials, this.getName());

        return authenticationInfo;
    }

    //2. doGetAuthorizationInfo：获得授权信息  → permissions
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addStringPermission("orderlist");
        return simpleAuthorizationInfo;
    }
}
